package com.itqf.listener;

import lombok.SneakyThrows;
import org.apache.ibatis.io.Resources;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.InputStream;
import java.util.Properties;

/**
 * projectName: rbacgp8
 *
 * @author: 赵伟风
 * time: 2021/8/12 14:43
 * description: 程序启动以后,加载匿名和认证资源配置读取到Properties类上!最终拦截器使用
 */
@WebListener
public class PropertiesLoader implements ServletContextListener {
    /**
     * Receives notification that the web application initialization
     * process is starting.
     *
     * <p>All ServletContextListeners are notified of context
     * initialization before any filters or servlets in the web
     * application are initialized.
     *
     * @param sce the ServletContextEvent containing the ServletContext
     *            that is being initialized
     */
    @SneakyThrows
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        InputStream stream = Resources.getResourceAsStream("url/anonymity.properties");
        InputStream stream1 = Resources.getResourceAsStream("url/authentication.properties");

        //程序启动的时候会触发!
        Properties anonymity = new Properties();
        anonymity.load(stream);

        Properties authentication = new Properties();
        authentication.load(stream1);


        //放入共享域对象
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute("anonymity",anonymity);
        servletContext.setAttribute("authentication",authentication);

    }

    /**
     * Receives notification that the ServletContext is about to be
     * shut down.
     *
     * <p>All servlets and filters will have been destroyed before any
     * ServletContextListeners are notified of context
     * destruction.
     *
     * @param sce the ServletContextEvent containing the ServletContext
     *            that is being destroyed
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
